package com.yry.security;

import java.security.Key;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Hex;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;
/**
 * 对称加密(Data Encryption Standard)数据加密标准
 * 比较老，现在基本不用
 * @author Administrator
 *
 */
public class ImoocDes {
	
	private String srcStr = "imooc security des";
	
	/**
	 * JDK DES加密，秘钥长度56位
	 */
	@Test
	public void jdkDes(){
		try {
			//生成Key;
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");
			keyGenerator.init(56);//初始化KEY的长度；
			//产生密钥；
			SecretKey  secretKey = keyGenerator.generateKey();
			//获得密钥
			byte[] key = secretKey.getEncoded();
			//KEY转换
			DESKeySpec desKeySpec = new DESKeySpec(key);
			SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
			Key convertSecretKey = factory.generateSecret(desKeySpec);
			
			//加密；
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(srcStr.getBytes());
			String resultStr = Hex.encodeHexString(result);
			System.out.println("JDK DES encrypt加密:"+resultStr);
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			resultStr = new String(result);
			System.out.println("JDK DES DECRYPT解密:"+resultStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * BC,DES,秘钥长度64位
	 */
	@Test
	public void bcDes(){
		try {
			Security.addProvider(new BouncyCastleProvider());
			//生成Key;
			KeyGenerator keyGenerator = KeyGenerator.getInstance("DES","BC");
			System.out.println(keyGenerator.getProvider());
			keyGenerator.init(56);//初始化KEY的长度；
			SecretKey  secretKey = keyGenerator.generateKey(); //产生密钥；
			byte[] key = secretKey.getEncoded(); //获得密钥
			
			//KEY转换
			DESKeySpec desKeySpec = new DESKeySpec(key);
			SecretKeyFactory factory=SecretKeyFactory.getInstance("DES");
			Key convertSecretKey = factory.generateSecret(desKeySpec);
			
			//加密；
			Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, convertSecretKey);
			byte[] result = cipher.doFinal(srcStr.getBytes());
			String resultStr = Hex.encodeHexString(result);
			System.out.println("BC DES encrypt:"+resultStr);
			
			//解密
			cipher.init(Cipher.DECRYPT_MODE, convertSecretKey);
			result = cipher.doFinal(result);
			resultStr = new String(result);
			System.out.println("BC DES DECRYPT: "+resultStr);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
